package text;

import utils.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

//第一种方法，此方法不能防止sql注入
public class Login {
    public static void main(String[] args) {
        //输入用户名及密码
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名：");
        String username = sc.nextLine();
        System.out.print("请输入密码：");
        String password = sc.nextLine();

        //通过返回值的类型，来判断是否能够登录成功
        boolean flag = new Login().login(username, password);
        //登录成功与失败的提示
        if (flag){
            System.out.println("登录成功！");
        } else {
            System.out.println("登录失败！");
        }
        sc.close();
    }

    public boolean login(String username, String password){
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        //如果用户名和密码都不为空，执行
        if (username != null && password != null){
            try {
                //注册驱动和连接数据库
                conn = JDBCUtil.getConnection();
                //输入sql语句，此语句不能防止sql注入
                String sql = "select * from user where username ='"+ username+ "' and password ='"+password+"'";
                stmt = conn.createStatement();
                rs = stmt.executeQuery(sql);
                return rs.next();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                JDBCUtil.close(rs, stmt, conn);
            }
        }
        //任意一个为空，直接返回false
        return false;
    }

}
